package leetcode2;

import java.util.Arrays;

public class LeetCodeMain128 {
    public int minSubArrayLen(int target, int[] nums) {
        int n=nums.length;
        if (n==0){
            return 0;
        }
        int count=Integer.MAX_VALUE;
        int[] sums=new int[n+1];
        for (int i = 1; i <= n; i++) {
            sums[i]=sums[i-1]+nums[i-1];
        }
        for (int i = 1; i <= n; i++) {
            int s=target+sums[i-1];
            int bound= Arrays.binarySearch(sums,s);
            if (bound < 0) {
                bound = -bound - 1;
            }
            if (bound <= n) {
                count = Math.min(count, bound - (i - 1));
            }
        }
        return count==Integer.MAX_VALUE?0:count;
    }
    public int minSubArrayLen1(int target, int[] nums) {
        int size=Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int sum=nums[i];
            int count=1;
            if (sum>=target){
                return 1;
            }
            for (int j = i+1; j < nums.length; j++) {
                count++;
                sum+=nums[j];
                if (sum>=target){
                    size=Math.min(count,size);
                    break;
                }
            }
        }
        return size==Integer.MAX_VALUE?0:size;
    }
}
